/**
 * to send notify SMS by template, there are some tag such as [webname] in the template,
 * so the program will load these parameters by CParamDao
 * by fuzhou huilin corp.ltd
 * LGX 2017骞?1鏈?10鏃?
 */
package com.fzrskj.cloud.free.sys.utils;

import com.fzrskj.cloud.free.api.API;
import com.fzrskj.cloud.free.core.tool.CDateTimeTool;
import com.fzrskj.cloud.free.core.utils.EncryptUtils;
import com.fzrskj.cloud.free.dic.utils.DicParamUtils;
import com.fzrskj.cloud.free.sys.bean.Param;
import com.fzrskj.cloud.free.sys.bean.SendResult;
import com.fzrskj.cloud.free.sys.bean.SysNotifyRecord;
import com.fzrskj.cloud.free.sys.bean.SysNotifyTemplate;
import com.fzrskj.cloud.free.sys.dao.CParamDao;
import com.fzrskj.cloud.free.sys.dao.SysNotifyRecordDao;
import com.fzrskj.cloud.free.sys.dao.SysNotifyTemplateDao;
import com.fzrskj.cloud.free.user.bean.UserAccountView;
import com.fzrskj.cloud.free.user.bean.UserIssue;
import com.fzrskj.cloud.free.user.utils.UserAccountUtils;
import ms.core.consts.SysErr;
import ms.core.object.CObject;
import ms.core.tool.StrTool;
import ms.core.tool.XmlCodeParser;
import net.sf.json.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.*;

public class SendSMSUtils extends CObject {

    //to load notify template
    private SysNotifyTemplate getNoitfyTemplate(String msgTypeValue) {
        SysNotifyTemplateDao tempDao = new SysNotifyTemplateDao();
        SysNotifyTemplate temp = tempDao.querySysNotifyTemplate(msgTypeValue);
        String code = tempDao.getErrCode();
        this.setErrCode(code);
        tempDao.dispose();
        return temp;
    }

    //to load web site parameter
    public void loadWebsiteParam(List<NameValuePair> params) {
        CParamDao dao = new CParamDao();
        List<Param> pms = dao.queryParam(1, null);
        dao.dispose();
        if (params == null) {
            return;
        }

        for (Param p : pms) {
            String pcode = p.getParamName().toLowerCase();
            params.add(new BasicNameValuePair("\\[" + pcode + "\\]", p.getParamValue()));
        }
    }

    //to replace tag
    private String replaceSMSTag(String info, List<NameValuePair> params) {
        for (NameValuePair p : params) {
            info = info.replaceAll(p.getName(), p.getValue());
        }
        return info;
    }

    //to add notify_record
    private int addSysNotifyRecord(String temp, String title, String content, String sender, String receiver, boolean sendOK) {
        SysNotifyRecord rd = new SysNotifyRecord();
        rd.setTitle(title);
        rd.setContent(content);
        rd.setMsgType(2);
        rd.setTempName(temp);
        rd.setReceiver(receiver);
        rd.setSender(sender);
        rd.setSendTime(new Date());
        if (sendOK) {
            rd.setState(2);
        } else {
            rd.setState(1);
        }
        SysNotifyRecordDao dao = new SysNotifyRecordDao();
        int ret = dao.addSysNotifyRecord(rd);
        dao.dispose();
        return ret;
    }

    //to send sms by template of msgTypeValue
    public SendResult sendSMS(String tempName, Map<String, Object> map, List<NameValuePair> params) {

        SendResult sendResult = new SendResult();
        int userId = StrTool.strToIntDef(map.get("userId").toString(), 0);
        try {
            do {
                String ifOpenSms = DicParamUtils.getParamValue("ifOpenSms");
                if (!ifOpenSms.equals("1")) {
                    sendResult.setCode(SysErr.SYS_MAIL_SEND_ERR);
                    sendResult.setId(-1);
                    sendResult.setMsg("没有开启短信接口！");
                    break;
                }
                //to get notify template
                SysNotifyTemplate temp = getNoitfyTemplate(tempName);
                if (temp == null) {
                    sendResult.setCode(SysErr.SYS_MAIL_SEND_ERR);
                    sendResult.setId(-1);
                    sendResult.setMsg("获得短信模板失败！");
                    break;
                }

                // replace param
                String content = replaceSMSTag(temp.getContent(), params);
                String title = replaceSMSTag(temp.getTitle(), params);

                String webname = DicParamUtils.getParamValue("webname");
                String comtel = DicParamUtils.getParamValue("comtel");
                String comfax = DicParamUtils.getParamValue("comfax");
                title = title.replace("[公司名]", webname);
                content = content.replace("[电话]", comtel);
                content = content.replace("[传真]", comfax);

//                String mobile = EncryptUtils.decodeSave(map.get("mobile").toString());

                //手机号码加密和未加密兼容处理
                String mobile = map.get("mobile").toString();
                if (mobile.length() > 12 ){
                    mobile = EncryptUtils.decodeSave(mobile);
                }
                JSONObject json = new JSONObject();
                json.put("Tel", mobile);
                json.put("Content", content);
                json.put("userId", userId);


                API api = new API();
                String sendState;
                String smsTypeString = DicParamUtils.getParamValue("smsServer");
                Integer smsType = StringUtils.isBlank(smsTypeString) ? 0 : Integer.valueOf(smsTypeString);

                String ret = api.SendSms(smsType, json.toString());
                JSONObject retJson = JSONObject.fromObject(ret);
                if (!("0").equals(retJson.getString("code"))) {
                    sendState = SysErr.CODE_FAILURE;
                    sendResult.setId(-1);
                } else {
                    sendState = SysErr.CODE_SUCCESS;
                    sendResult.setId(1);
                }

                //get sender and sendstate
                //String sender = retJson.getString("account");

                //add send record to sys_notify_record
                addSysNotifyRecord(tempName, title, content, smsType.toString(), mobile, sendState.equals(SysErr.CODE_SUCCESS));
                sendResult.setCode(sendState);
                //sendResult.setId(rid);
                sendResult.setMsg(XmlCodeParser.codeOfMessage(sendState));
            } while (false);
        } catch (Exception e) {
            StringWriter sw = new StringWriter();
            e.printStackTrace(new PrintWriter(sw, true));
            SysRunTimeLogUtils.addLog(this, userId, tempName, "发送报文=【" + params + "】,接收异常=【" + sw.toString() + "】");
        }
        return sendResult;
    }

    /*================================== SendSMS Service processing module  =============================================*/

    //to send confirm_mod_success sms to user by userId（短信通知）
    private SendResult sendModPassSMS(int uid) {
        SendResult ret = new SendResult();
        //load user account info
        UserAccountUtils uaUtils = new UserAccountUtils();
        UserAccountView uv = uaUtils.queryUserAccountViewByUid(uid);
        String code = uaUtils.getErrCode();
        if (!code.equals(SysErr.CODE_SUCCESS)) {
            ret.setCode(SysErr.DB_UNKNOWN_ERR);
            ret.setId(-1);
            ret.setMsg(XmlCodeParser.codeOfMessage(SysErr.DB_UNKNOWN_ERR));
            return ret;
        }
        if (uv == null) {
            ret.setCode(SysErr.USER_NOT_EXISTS);
            ret.setId(-1);
            ret.setMsg(XmlCodeParser.codeOfMessage(SysErr.USER_NOT_EXISTS));
            return ret;
        }

        Map<String, Object> map = new HashMap<String, Object>();
        map.put("mobile", uv.getMobile());
        map.put("userId", uv.getUserId());

        //create mod_passsword_time
        Date date = new Date();
        String modTime = CDateTimeTool.formatDateTime(date, "yyyy-MM-dd HH:mm:ss");

        List<NameValuePair> params = new ArrayList<NameValuePair>();
        loadWebsiteParam(params);
        params.add(new BasicNameValuePair("\\[时间\\]", modTime));

        return sendSMS("findPswSms", map, params);
    }

    //to send issue sms to user by userId（短信通知）
    private SendResult sendIssue(UserIssue issue) {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("mobile", issue.getMobile());
        map.put("userId", issue.getUserId());

        //create mod_passsword_time
        Date date = new Date();
        String modTime = CDateTimeTool.formatDateTime(date, "yyyy-MM-dd HH:mm:ss");

        List<NameValuePair> params = new ArrayList<NameValuePair>();
        loadWebsiteParam(params);
        params.add(new BasicNameValuePair("\\[时间\\]", modTime));
        params.add(new BasicNameValuePair("\\[工单号\\]", String.valueOf(issue.getParentIssueId())));
        params.add(new BasicNameValuePair("\\[工单标题\\]", String.valueOf(issue.getBusinessName())));

        return sendSMS("woWaitConfirmSms", map, params);
    }
    /*=================================== public static functions =======================================================*/

    /**
     * @return
     * @ send confirm_mod_success SMS by uid
     */
    public static SendResult sendAccountModPassSMS(int uid) {
        SendSMSUtils sms = new SendSMSUtils();
        return sms.sendModPassSMS(uid);
    }

    /**
     * @return
     * @ send issue SMS by uid
     */
    public static SendResult sendIssueSMS(UserIssue issue) {
        SendSMSUtils sms = new SendSMSUtils();
        return sms.sendIssue(issue);
    }
}